/**
 * Copyright 2009 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.sapien.guice;

import java.lang.annotation.Annotation;
import java.util.Map;

import org.apache.struts2.util.ObjectFactoryDestroyable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.ScopeAnnotation;
import com.google.inject.Stage;
import com.google.inject.servlet.ServletModule;
import com.opensymphony.xwork2.ObjectFactory;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.entities.InterceptorConfig;
import com.opensymphony.xwork2.inject.Inject;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * Guice Implementation of the Xwork ObjectFactory for struts2.
 * @author Adam
 * @version $Id: GuiceObjectFactory.java 29 2010-01-04 05:25:44Z a.ruggles $
 * 
 * Created on Feb 5, 2009 at 9:22:13 PM 
 */
public class GuiceObjectFactory extends ObjectFactory implements ObjectFactoryDestroyable {
	/**
	 * Guice Injector.
	 */
	protected volatile Injector injector;

	/**
	 * Serial Version UID.
	 */
	private static final long serialVersionUID = -4144312522455955045L;

	/**
	 * Returns true if the interceptor class has a scope annotation.
	 * @param interceptorClass The interceptor class to check.
	 * @return True if the interceptor class has a scope annotation.
	 */
	private static boolean hasScope(final Class<? extends Interceptor> interceptorClass) {
		boolean found = false;
        for (Annotation annotation : interceptorClass.getAnnotations()) {
            if (annotation.annotationType().isAnnotationPresent(ScopeAnnotation.class)) {
            	found = true;
            }
        }
        return found;
    }

	/**
	 * Development Mode Flag.
	 */
	private boolean developmentMode = false;

	/**
     * The <code>Logger</code> is used by the application to generate a log messages.
     */
    private static final Logger LOG = LoggerFactory.getLogger(GuiceObjectFactory.class);

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.ObjectFactory#buildBean(java.lang.Class, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public Object buildBean(final Class clazz, final Map extraContext) {
        final Object obj = getInjector().getInstance(clazz);
        injectInternalBeans(obj);
        return obj;
    }

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.ObjectFactory#buildInterceptor(
	 * com.opensymphony.xwork2.config.entities.InterceptorConfig, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public Interceptor buildInterceptor(final InterceptorConfig interceptorConfig, final Map params)
		throws ConfigurationException {
		// Ensure the interceptor class is present.
		Class<? extends Interceptor> interceptorClass;
		try {
			interceptorClass = getClassInstance(interceptorConfig.getClassName());
		} catch (ClassNotFoundException e) {
			throw new ConfigurationException(e);
		}
		if (hasScope(interceptorClass)) {
			throw new ConfigurationException("Scoping interceptors is not currently supported. Please "
					+ "remove the scope annotation from [" + interceptorClass.getName() + "].");
		}
		final Interceptor interceptor = super.buildInterceptor(interceptorConfig, params);
		getInjector().injectMembers(interceptor);
		return interceptor;
	}

	/**
	 * Creates the Guice Injector.
	 */
	private void createInjector() {
		LOG.info("Creating Guice injector...");
		Stage stage;
		if (developmentMode) {
			LOG.info("Using Development Mode");
			stage = Stage.DEVELOPMENT;
		} else {
			LOG.info("Using Production Mode");
			stage = Stage.PRODUCTION;
		}
		injector = Guice.createInjector(stage, new ServletModule(), new ConfigModule());
		LOG.info("Injector created successfully.");
	}

	/**
	 * {@inheritDoc}
	 * @see org.apache.struts2.util.ObjectFactoryDestroyable#destroy()
	 */
	public void destroy() {
		LOG.debug("Object Factory destroy method has been called");
	}

	/**
	 * Returns the Guice Injector.  If there is no injector it will create the injector.
	 * @return The Guice Injector.
	 */
	public Injector getInjector() {
		if (injector == null) {
			synchronized (this) {
				if (injector == null) {
					createInjector();
				}
			}
		}
		return injector;
	}

	/**
	 * Returns developmentMode.
	 * @return the developmentMode.
	 */
	public boolean isDevelopmentMode() {
		return developmentMode;
	}

	/**
	 * {@inheritDoc}
	 * @see com.opensymphony.xwork2.ObjectFactory#isNoArgConstructorRequired()
	 */
	@Override
    public boolean isNoArgConstructorRequired() {
        return false;
    }

	/**
	 * Sets developmentMode.
	 * @param developmentMode the developmentMode to set.
	 */
	@Inject(value = "struts.devMode", required = false)
	public void setDevelopmentMode(final String developmentMode) {
		if (developmentMode != null) {
			this.developmentMode = "true".equalsIgnoreCase(developmentMode.trim());
		}
	}
}
